import logging
import os
import logging.handlers
from config import settings


class LogHandler(object):
    """日志处理工具类"""

    def __init__(self):
        if not os.path.exists(settings.LOG_FILE_PATH):
            os.makedirs(settings.LOG_FILE_PATH)
        self.name = settings.LOG_NAME
        self.filename = settings.LOG_FILE_NAME

        self.charset = settings.LOG_CHARSET
        self.log_backup_count = settings.LOG_BACKUP_COUNT
        self.when = settings.LOG_WHEN

    def get_logger(self):
        # 创建logger，如果参数name表示日志器对象名，name为空则返回root logger
        _logger = logging.getLogger(self.name)
        # 务必设置一个初始化的日志等级
        _logger.setLevel(logging.DEBUG)
        # 这里进行判断，如果logger.handlers列表为空则添加，否则多次调用log日志函数会重复添加
        if not _logger.handlers:
            # 创建handler
            file_handler = logging.handlers.TimedRotatingFileHandler(
                filename=self.filename,
                when=self.when,
                backupCount=self.log_backup_count,
                encoding=self.charset
            )
            console_handler = logging.StreamHandler()

            # 单独设置logger日志等级
            file_handler.setLevel(logging.INFO)
            # 设置输出日志格式
            file_formatter = logging.Formatter(
                fmt="{asctime} {name} {levelname} {filename}:{lineno} {message}",
                datefmt="%Y-%m-%d %H:%M:%S",
                style="{"
            )

            console_formatter = logging.Formatter(
                fmt="{asctime} {name} {levelname} {filename}:{lineno} {message}",
                datefmt="%Y-%m-%d %H:%M:%S",
                style="{")

            # 为handler指定输出格式
            file_handler.setFormatter(file_formatter)
            console_handler.setFormatter(console_formatter)
            # 为logger添加的日志处理器
            _logger.addHandler(file_handler)
            _logger.addHandler(console_handler)

        return _logger  # 直接返回logger


logger = LogHandler().get_logger()
